﻿//KhoaVV
//Chua cac ham mac dinh duoc su dung di su dung lai nhieu lan

using System;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using mojoPortal.Net;
using mojoPortal.Web;

namespace ud_gSDMS.Code_Service
{
   public class Library
    {
        #region Declare
        static DateTime mToday;
        #endregion
        #region Property
        #endregion Property
        static public DataTable LINQToDataTable(System.Data.Linq.DataContext ctx, object query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            IDbCommand cmd = ctx.GetCommand(query as IQueryable);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = (SqlCommand) cmd;
            DataTable dt = new DataTable("ListAssign");
            try
            {
                cmd.Connection.Open();
                //adapter.FillSchema(dt, SchemaType.Source);
                adapter.Fill(dt);
                dt.Columns[0].Unique = false;
            }
            catch
            {
            }
            finally
            {
                cmd.Connection.Close();
            }
            return dt;
        }
        static public void AddColSTTTable(DataTable data, string name)
        {
            DataColumn colSTT = new DataColumn(name, Type.GetType("System.Int32"));
            data.Columns.Add(colSTT);
            colSTT.SetOrdinal(0);
            int count = data.Rows.Count;
            for (int i = 0; i < count; i++)
            {
                data.Rows[i]["STT"] = i + 1;
            }
        }
        //KhoaVV - 02/04/2010
        //Ma hoa chuoi don gian
        public static string EncodeDecode(string data, bool encode)
        {
            if (encode)
                try
                {
                    byte[] encData_byte = new byte[data.Length];
                    encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
                    string encodedData = Convert.ToBase64String(encData_byte);
                    return encodedData;
                }
                catch
                {
                    return "";
                }
            else
                try
                {
                    System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
                    System.Text.Decoder utf8Decode = encoder.GetDecoder();

                    byte[] todecode_byte = Convert.FromBase64String(data);
                    int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                    char[] decoded_char = new char[charCount];
                    utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                    string result = new String(decoded_char);
                    return result;
                }
                catch
                {
                    return "";
                }
        }
        public static string Encrypt(string toEncrypt, bool isEncrypt)
        {
            const string SECURITYKEY = "3ecur1tyKey";
            if (isEncrypt)
            {
                byte[] keyArray;
                byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(SECURITYKEY));
                hashmd5.Clear();

                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                tdes.Key = keyArray;
                tdes.Mode = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;

                ICryptoTransform cTransform = tdes.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                tdes.Clear();
                return Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            else
            {
                byte[] keyArray;
                byte[] toEncryptArray = Convert.FromBase64String(toEncrypt);

                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(SECURITYKEY));
                hashmd5.Clear();

                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                tdes.Key = keyArray;
                tdes.Mode = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;

                ICryptoTransform cTransform = tdes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                tdes.Clear();
                return UTF8Encoding.UTF8.GetString(resultArray);
            }
        }
        
        public static string RemoveSign4VietnameseString(string str)
        {
            //Tiến hành thay thế , lọc bỏ dấu cho chuỗi
            string[] VietnameseSigns = new string[] { "aAeEoOuUiIdDyY", "áàạảãâấầậẩẫăắằặẳẵ", "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ", "éèẹẻẽêếềệểễ", "ÉÈẸẺẼÊẾỀỆỂỄ", "óòọỏõôốồộổỗơớờợởỡ", "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ", "úùụủũưứừựửữ", "ÚÙỤỦŨƯỨỪỰỬỮ", "íìịỉĩ", "ÍÌỊỈĨ", "đ", "Đ", "ýỳỵỷỹ", "ÝỲỴỶỸ" };
            for (int i = 1; i < VietnameseSigns.Length; i++)
            {
                for (int j = 0; j < VietnameseSigns[i].Length; j++)
                    str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
            }
            return str;
        }

        public static void SendMail(string fromAddress, string toAddress,string emailCc, string emailBcc, string subject, string message, System.Guid siteGuid)
        {
            SmtpSettings smtpSettings = SiteUtils.GetSmtpSettings();
            var messageTask = new EmailMessageTask(smtpSettings)
                                  {
                                      Subject = subject,
                                      EmailFrom = fromAddress,
                                      EmailTo = toAddress,
                                      EmailCc = emailCc,
                                      EmailBcc = emailBcc,
                                      TextBody = message,
                                      SiteGuid = siteGuid,
                                      PreferredEncoding = "utf-8"
                                  };
            messageTask.QueueTask();
            WebTaskManager.StartOrResumeTasks();
        }

        public static void SendMailFromUser(string userEmail, string userPass, string server, int port, bool isAuthen, bool isSSL, string fromAddress, string toAddress, string emailCc, string emailBcc, string subject, string message, System.Guid siteGuid)
        {
            SmtpSettings smtpSettings = SiteUtils.GetSmtpSettings();
            smtpSettings.User = userEmail;
            smtpSettings.Password = userPass;
            smtpSettings.Server = server;
            smtpSettings.Port = port;
            smtpSettings.RequiresAuthentication = isAuthen;
            smtpSettings.UseSsl = isSSL;

            var messageTask = new EmailMessageTask(smtpSettings)
            {
                Subject = subject,
                EmailFrom = fromAddress,
                EmailTo = toAddress,
                EmailCc = emailCc,
                EmailBcc = emailBcc,
                TextBody = message,
                SiteGuid = siteGuid,
                PreferredEncoding = "utf-8"
            };
            messageTask.QueueTask();
            WebTaskManager.StartOrResumeTasks();
        }
       /// <summary>
       /// 
       /// </summary>
       /// <param name="enddate">vi-VN or en-US or...</param>
       /// <param name="format"></param>
       /// <returns></returns>
        public static string GiveAlarm(object enddate, string format)
        {
            try
            {
                if (enddate == null) return "";
                var d = format != "" ? Convert.ToDateTime(enddate, new CultureInfo(format)) : Convert.ToDateTime(enddate);
                var now = DateTime.Now;
                if (now.AddDays(8).Date <= d.Date && d.Date <= now.AddDays(14).Date) return "baodong1";
                if (now.AddDays(0).Date <= d.Date && d.Date <= now.AddDays(8).Date) return "baodong2";
                if (d.Date < now.Date) return "baodong3";
            }
            catch
            { }
            return "";
        }

        public static string NumberStringNoDot(string str)
        {
            str = str.Trim(",./';".ToCharArray());
            return str;
        }

        public static string NumberSmallThanTenToString(char num)
        {
            switch (num)
            {
                case '0':
                    return "không";
                    break;
                case '1':
                    return "một";
                    break;
                case '2':
                    return "hai";
                    break;
                case '3':
                    return "ba";
                    break;
                case '4':
                    return "bốn";
                    break;
                case '5':
                    return "năm";
                    break;
                case '6':
                    return "sáu";
                    break;
                case '7':
                    return "bảy";

                    break;
                case '8':
                    return "tám";
                    break;
                case '9':
                    return "chín";
                    break;

            }
            return "";
        }

        public static string NumberSmallThanThousandToString(string num)
        {
            if (num.Length > 3) return "";
            if (num.Equals("000")) return "";
            if (num.Length == 2) return NumberSmallThanHundredToString(num, false);
            if (num.Length == 1) return NumberSmallThanTenToString(num[0]);
            if (num.Length == 0) return "";

            switch (num[0])
            {
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    return NumberSmallThanTenToString(num[0]) + " trăm " + NumberSmallThanHundredToString(num.Substring(1,2), true);
                break;

            }
            return "";
        }

        public static string NumberSmallThanHundredToString(string num , bool isOdd)
        {
            if (num.Length > 2) return "";
            if (num == "00") return "";

            switch (num[0])
            {
                case '0':
                    if (isOdd)
                        return "lẻ " + NumberSmallThanTenToString(num[1]);
                    else
                        return NumberSmallThanTenToString(num[1]);
                    break;
                case '1':
                    return "mười " + (num[1] != '0' ? NumberSmallThanTenToString(num[1]) : "");
                    break;
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    return NumberSmallThanTenToString(num[0]) + " mươi " + (num[1] != '0' ? NumberSmallThanTenToString(num[1]) : "");
                    break;

            }
            return "";
        }

        public static string NumberSmallThanBillionToString(string num)
        {
            int len = num.Length;
            double count = (double)(len / 3.0);


            if (count > 2)
            {

                return NumberSmallThanThousandToString(num.Substring(0, len - 6)) + " triệu " + NumberSmallThanThousandToString(num.Substring(len - 6, 3)) + " ngàn " + NumberSmallThanThousandToString(num.Substring(len - 3, 3));
            }
            else
            if (count > 1)
            {
                return NumberSmallThanThousandToString(num.Substring(0, len - 3)) + " ngàn " + NumberSmallThanThousandToString(num.Substring(len - 3, 3));
            }
            else
                if (count > 0)
                {
                    return NumberSmallThanThousandToString(num);
             
                }

            return "";

        }

       

        public static string NumberToString(string num)
        {
            int count = num.Length;
            int level = count / 9;
            int i = count - level * 9;

            string str = NumberSmallThanBillionToString(num.Substring(0, i));

            for (; i < count; i += 9)
            {
                str += " tỷ ";
                str += NumberSmallThanBillionToString(num.Substring(i, 9));
            }

            return str;
        }
    }
}
